﻿from __future__ import division
from datoselophantgame import datoselophantgame
import urllib,ast,time,win32gui


def datosiniciogame(nombrejugador,server,key,dicconversion2):
##  Funcion busca datos de enemigos en elophant. Los busca hasta que estan disponibles.
##  Devuelve un diccionario para cada equipo de la forma: {"campeon","stats","name"}
##  Además "stats" es otro diccionario de la forma: {"elosolo5v5","elosolo5v5season2","statscampeon":{"jugadas","victorias","avgkills","avgdeaths","avgassists" },"statscampeonseason2"}
##    
##    Server puede ser [euw,na,eune]  mas?
##    return teamonestats,teamtwostats


    try:
        
##        start_time = time.time()    
##        key="Z1TMfh3wAFvk4cRejiXn"

            
        encontrado=0
        while encontrado==0:
            try:
                filehandle = urllib.urlopen('http://elophant.com/api/v1/{0}/getInProgressGameInfo?summonerName={1}&key={2}'.format(server,nombrejugador,key))
                var=filehandle.read()
                if "true" in var:
                    var=var.replace('true','1')
                if "false" in var:
                    var=var.replace('false','0')
                dicgame=ast.literal_eval(var)
                filehandle.close()
##                elapsed= time.time() - start_time
                if len(dicgame)>1:
                    encontrado=1
##                    print dicgame
##                    print elapsed
                else:
                    time.sleep(1)
##                print dicgame,elapsed
##                encontrado=1

            except:
                time.sleep(1)
                
##        dicconversion2={'131': 'Diana', '134': 'Syndra', '24': 'Jax', '25': 'Morgana', '26': 'Zilean', '27': 'Singed', '20': 'Nunu', '21': 'Miss Fortune', '22': 'Ashe', '23': 'Tryndamere', '28': 'Evelynn', '29': 'Twitch', '4': 'Twisted Fate', '8': 'Vladimir', '120': 'Hecarim', '121': "Kha'Zix", '122': 'Darius', '126': 'Jayce', '59': 'Jarvan IV', '58': 'Renekton', '55': 'Katarina', '54': 'Malphite', '57': 'Maokai', '56': 'Nocturne', '51': 'Caitlyn', '50': 'Swain', '53': 'Blitzcrank', '115': 'Ziggs', '114': 'Fiora', '117': 'Lulu', '89': 'Leona', '111': 'Nautilus', '110': 'Varus', '113': 'Sejuani', '112': 'Viktor', '82': 'Mordekaiser', '83': 'Yorick', '80': 'Pantheon', '81': 'Ezreal', '86': 'Garen', '84': 'Akali', '85': 'Kennen', '3': 'Galio', '7': 'LeBlanc', '102': 'Shyvana', '103': 'Ahri', '101': 'Xerath', '106': 'Volibear', '107': 'Rengar', '104': 'Graves', '105': 'Fizz', '39': 'Irelia', '38': 'Kassadin', '33': 'Rammus', '32': 'Amumu', '31': "Cho'Gath", '30': 'Karthus', '37': 'Sona', '36': 'Dr. Mundo', '35': 'Shaco', '34': 'Anivia', '60': 'Elise', '61': 'Orianna', '62': 'Wukong', '63': 'Brand', '64': 'Lee Sin', '67': 'Vayne', '68': 'Rumble', '69': 'Cassiopeia', '2': 'Olaf', '6': 'Urgot', '99': 'Lux', '98': 'Shen', '91': 'Talon', '90': 'Malzahar', '92': 'Riven', '96': "Kog'Maw", '11': 'Master Yi', '10': 'Kayle', '13': 'Ryze', '12': 'Alistar', '15': 'Sivir', '14': 'Sion', '17': 'Teemo', '16': 'Soraka', '19': 'Warwick', '18': 'Tristana', '238': 'Zed', '48': 'Trundle', '119': 'Draven', '44': 'Taric', '45': 'Veigar', '42': 'Corki', '43': 'Karma', '40': 'Janna', '41': 'Gangplank', '1': 'Annie', '5': 'Xin Zhao', '9': 'Fiddlesticks', '143': 'Zyra', '77': 'Udyr', '76': 'Nidalee', '75': 'Nasus', '74': 'Heimerdinger', '72': 'Skarner', '79': 'Gragas', '78': 'Poppy'}        
        #En la siguiente linea hay dicgame comentado pero no se ve
##        dicgame={'lastModifiedDate': '0001-01-01 08:00:00Z', 'game': {'queueTypeName': 'RANKED_SOLO_5x5', 'spectatorsAllowed': 'NONE', 'gameMode': 'CLASSIC', 'mapId': 1, 'gameState': 'IN_PROGRESS', 'spectatorDelay': 0, 'teamTwo': [{'index': 0, 'summonerInternalName': 'achumort', 'summonerName': 'Achumort', 'originalPlatformId': 'EUW1', 'pickTurn': 2, 'profileIconId': 10, 'timeAddedToQueue': 1353586524352L, 'clientInSynch': 1, 'queueRating': 0, 'botDifficulty': 'NONE', 'teamOwner': 1, 'originalAccountNumber': 29931805, 'lastSelectedSkinIndex': 0, 'pickMode': 0, 'summonerId': 25513809, 'accountId': 29931805}, {'index': 0, 'summonerInternalName': 'gummble', 'summonerName': 'Gummble', 'originalPlatformId': 'EUW1', 'pickTurn': 2, 'profileIconId': 508, 'timeAddedToQueue': 1353586538952L, 'clientInSynch': 1, 'queueRating': 0, 'botDifficulty': 'NONE', 'teamOwner': 1, 'originalAccountNumber': 35509555, 'lastSelectedSkinIndex': 0, 'pickMode': 0, 'summonerId': 31810727, 'accountId': 35509555}, {'index': 0, 'summonerInternalName': 'volturnos', 'summonerName': 'volturnos', 'originalPlatformId': 'EUW1', 'pickTurn': 4, 'profileIconId': 1, 'timeAddedToQueue': 1353586652488L, 'clientInSynch': 1, 'queueRating': 0, 'botDifficulty': 'NONE', 'teamOwner': 1, 'originalAccountNumber': 32321463, 'lastSelectedSkinIndex': 0, 'pickMode': 0, 'summonerId': 28822652, 'accountId': 32321463}, {'index': 0, 'summonerInternalName': 'ejector', 'summonerName': 'Ejector', 'originalPlatformId': 'EUW1', 'pickTurn': 4, 'profileIconId': 24, 'timeAddedToQueue': 1353586531530L, 'clientInSynch': 1, 'queueRating': 0, 'botDifficulty': 'NONE', 'teamOwner': 1, 'originalAccountNumber': 23941106, 'lastSelectedSkinIndex': 0, 'pickMode': 0, 'summonerId': 20697135, 'accountId': 23941106}, {'index': 0, 'summonerInternalName': 'londrandir', 'summonerName': 'Londrandir', 'originalPlatformId': 'EUW1', 'pickTurn': 6, 'profileIconId': 27, 'timeAddedToQueue': 1353586531530L, 'clientInSynch': 1, 'queueRating': 0, 'botDifficulty': 'NONE', 'teamOwner': 1, 'originalAccountNumber': 24086829, 'lastSelectedSkinIndex': 0, 'pickMode': 0, 'summonerId': 20786311, 'accountId': 24086829}], 'roomPassword': '6XUX6QTM4Nl9AZVU', 'playerChampionSelections': [{'selectedSkinIndex': 0, 'summonerInternalName': 'volturnos', 'championId': 5, 'spell1Id': 11, 'spell2Id': 4}, {'selectedSkinIndex': 0, 'summonerInternalName': 'luisonoff', 'championId': 56, 'spell1Id': 11, 'spell2Id': 4}, {'selectedSkinIndex': 0, 'summonerInternalName': 'storkuk1337', 'championId': 22, 'spell1Id': 4, 'spell2Id': 14}, {'selectedSkinIndex': 0, 'summonerInternalName': 'damir925', 'championId': 17, 'spell1Id': 7, 'spell2Id': 14}, {'selectedSkinIndex': 0, 'summonerInternalName': 'londrandir', 'championId': 24, 'spell1Id': 4, 'spell2Id': 14}, {'selectedSkinIndex': 0, 'summonerInternalName': 'laleluli', 'championId': 82, 'spell1Id': 4, 'spell2Id': 14}, {'selectedSkinIndex': 0, 'summonerInternalName': 'ejector', 'championId': 106, 'spell1Id': 4, 'spell2Id': 3}, {'selectedSkinIndex': 0, 'summonerInternalName': 'gummble', 'championId': 61, 'spell1Id': 14, 'spell2Id': 4}, {'selectedSkinIndex': 0, 'summonerInternalName': 'achumort', 'championId': 81, 'spell1Id': 7, 'spell2Id': 4}, {'selectedSkinIndex': 0, 'summonerInternalName': 'vengefultesla', 'championId': 89, 'spell1Id': 4, 'spell2Id': 3}], 'id': 603142891, 'teamOne': [{'index': 0, 'summonerInternalName': 'damir925', 'summonerName': 'damir925', 'originalPlatformId': 'EUW1', 'pickTurn': 1, 'profileIconId': 518, 'timeAddedToQueue': 1353586649850L, 'clientInSynch': 1, 'queueRating': 0, 'botDifficulty': 'NONE', 'teamOwner': 1, 'originalAccountNumber': 30454002, 'lastSelectedSkinIndex': 0, 'pickMode': 0, 'summonerId': 26244781, 'accountId': 30454002}, {'index': 0, 'summonerInternalName': 'luisonoff', 'summonerName': 'LuisOnOff', 'originalPlatformId': 'EUW1', 'pickTurn': 3, 'profileIconId': 20, 'timeAddedToQueue': 1353586661639L, 'clientInSynch': 1, 'queueRating': 0, 'botDifficulty': 'NONE', 'teamOwner': 1, 'originalAccountNumber': 24586538, 'lastSelectedSkinIndex': 0, 'pickMode': 0, 'summonerId': 21184632, 'accountId': 24586538}, {'index': 0, 'summonerInternalName': 'vengefultesla', 'summonerName': 'VengefulTesla', 'originalPlatformId': 'EUW1', 'pickTurn': 3, 'profileIconId': 28, 'timeAddedToQueue': 1353586560738L, 'clientInSynch': 1, 'queueRating': 0, 'botDifficulty': 'NONE', 'teamOwner': 1, 'originalAccountNumber': 32633557, 'lastSelectedSkinIndex': 0, 'pickMode': 0, 'summonerId': 28876185, 'accountId': 32633557}, {'index': 0, 'summonerInternalName': 'laleluli', 'summonerName': 'laleluli', 'originalPlatformId': 'EUW1', 'pickTurn': 5, 'profileIconId': 21, 'timeAddedToQueue': 1353586504949L, 'clientInSynch': 1, 'queueRating': 0, 'botDifficulty': 'NONE', 'teamOwner': 1, 'originalAccountNumber': 21871490, 'lastSelectedSkinIndex': 0, 'pickMode': 0, 'summonerId': 19209662, 'accountId': 21871490}, {'index': 0, 'summonerInternalName': 'storkuk1337', 'summonerName': 'StORkUk1337', 'originalPlatformId': 'EUW1', 'pickTurn': 5, 'profileIconId': 22, 'timeAddedToQueue': 1353586656104L, 'clientInSynch': 1, 'queueRating': 0, 'botDifficulty': 'NONE', 'teamOwner': 1, 'originalAccountNumber': 32054039, 'lastSelectedSkinIndex': 0, 'pickMode': 0, 'summonerId': 28208261, 'accountId': 32054039}], 'queuePosition': 0, 'passwordSet': 1, 'terminatedCondition': 'NOT_TERMINATED', 'optimisticLock': 21, 'statusOfParticipants': '1111111111', 'bannedChampions': [{'pickTurn': 1, 'championId': 53, 'teamId': 100}, {'pickTurn': 2, 'championId': 54, 'teamId': 200}, {'pickTurn': 3, 'championId': 98, 'teamId': 100}, {'pickTurn': 4, 'championId': 122, 'teamId': 200}, {'pickTurn': 5, 'championId': 25, 'teamId': 100}, {'pickTurn': 6, 'championId': 32, 'teamId': 200}], 'observers': [], 'maxNumPlayers': 10, 'gameStartTime': '1970-01-01 00:00:00Z', 'name': 'Match-603142891', 'pickTurn': 8, 'gameTypeConfigId': 2, 'gameType': 'RANKED_GAME'}, 'gameName': 'match-603142891', 'playerCredentials': {'gameId': 603142891, 'observer': 1, 'playerId': 24586538, 'observerServerIp': '95.172.65.26', 'observerServerPort': 8088, 'lastSelectedSkinIndex': 0, 'observerEncryptionKey': '6nj2ElH1j/I3ZNGcCD/swW9qaWGj7iT+'}, 'reconnectDelay': 179}     
        teamone={}
        teamtwo={}
        campactual={}
        ## Veo componentes equipos
        for i in range(5):
            teamone[i]={"name":dicgame["game"]["teamOne"][i]["summonerName"],"internalname":dicgame["game"]["teamOne"][i]['summonerInternalName'], "accountid":dicgame["game"]["teamOne"][i]['accountId'],"pickturn":dicgame["game"]["teamOne"][i]['pickTurn']}
        for i in range(5):
            teamtwo[i]={"name":dicgame["game"]["teamTwo"][i]["summonerName"],"internalname":dicgame["game"]["teamTwo"][i]['summonerInternalName'], "accountid":dicgame["game"]["teamTwo"][i]['accountId'],"pickturn":dicgame["game"]["teamTwo"][i]['pickTurn']}
        ## Veo campeon juega cada uno
        for i in range(10):
            campactual[dicgame["game"]['playerChampionSelections'][i]['summonerInternalName']]=dicgame["game"]['playerChampionSelections'][i]['championId']
        ## Obtengo stats de cada jugador con ese campeon
        teamonestats={}
        teamtwostats={}
        for i in range(5):
            teamonestats[i]={"campeon":dicconversion2['{0}'.format(campactual[teamone[i]["internalname"]])],"stats":datoselophantgame(teamone[i]["accountid"],server,key,campactual[teamone[i]["internalname"]]),"name":teamone[i]["name"]}
        for i in range(5):
            teamtwostats[i]={"campeon":dicconversion2['{0}'.format(campactual[teamtwo[i]["internalname"]])],"stats":datoselophantgame(teamtwo[i]["accountid"],server,key,campactual[teamtwo[i]["internalname"]]),"name":teamtwo[i]["name"]}

        
        return teamonestats,teamtwostats

    except:
        return 0
        pass
